<template>
  <view class="refund-manage-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">退款管理</text>
      <text class="nav-add" @click="showAddModal"></text>
    </view>

    <!-- 标签页 -->
    <view class="tabs-section">
      <view class="tabs-container">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'refundable' }"
          @click="switchTab('refundable')"
        >
          可退款
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'refunded' }"
          @click="switchTab('refunded')"
        >
          已退款
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="请输入订单号、房东姓名或手机号"
        :clearable="true"
        @confirm="onSearch"
        @clear="onClearSearch"
      />
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view 
        class="order-item" 
        v-for="item in orderList" 
        :key="item.id"
        @click="viewDetail(item)"
      >
        <view class="item-header">
          <text class="item-title">{{ getTypeText(item.type) }}</text>
          <text class="item-status" :class="getStatusClass(item)">
            {{ getStatusText(item) }}
          </text>
        </view>
        <view class="item-content">
          <view class="item-row">
            <text class="item-label">订单号：</text>
            <text class="item-value">{{ item.orderNo }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">订单金额：</text>
            <text class="item-value amount">¥{{ item.totalPrice }}</text>
          </view>
          <view class="item-row" v-if="item.type != 2">
            <text class="item-label">房东姓名：</text>
            <text class="item-value">{{ item.chName || '未填写' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">手机号：</text>
            <text class="item-value">{{ item.chMobile || '未填写' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">详细地址：</text>
            <text class="item-value">{{ item.type != 2 ? item.remark : item.chName }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">支付渠道：</text>
            <text class="item-value">{{ getPayChannelText(item.payChannel) }}</text>
          </view>
          <view class="item-row" v-if="item.payTime">
            <text class="item-label">支付时间：</text>
            <text class="item-value">{{ formatDate(item.payTime) }}</text>
          </view>
          <view class="item-row" v-if="item.refundTime && activeTab === 'refunded'">
            <text class="item-label">退款时间：</text>
            <text class="item-value">{{ formatDate(item.refundTime) }}</text>
          </view>
          <view class="item-row" v-if="item.refundAmount && activeTab === 'refunded'">
            <text class="item-label">退款金额：</text>
            <text class="item-value amount">¥{{ item.refundAmount }}</text>
          </view>
        </view>
        <view class="item-footer">
          <view class="item-actions" v-if="activeTab === 'refundable' && item.orderStatus === 1">
            <text class="action-btn refund" @click.stop="refundOrder(item)">退款</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="orderList.length === 0 && !loading">
      <text class="empty-text">{{ activeTab === 'refundable' ? '暂无可退款订单' : '暂无已退款记录' }}</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { getDoorInfoList, submitRefund } from '@/api/door/info'

export default {
  data() {
    return {
      orderList: [],
      loading: false,
      searchKeyword: '',
      selectedType: '',
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      activeTab: 'refundable' // 当前激活的标签页
    }
  },
  onLoad() {
    this.loadData()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 显示新增弹窗
    showAddModal() {
      this.$modal.msgInfo('新增功能开发中')
    },
    
    // 切换标签页
    switchTab(tab) {
      this.activeTab = tab
      this.pageNum = 1
      this.loadData()
    },
    
    // 显示类型选择器
    showTypePicker() {
      uni.showActionSheet({
        itemList: ['全部类型', '运维费', '门禁卡', '人脸'],
        success: (res) => {
          const typeMap = ['', 1, 3, 4]
          this.selectedType = typeMap[res.tapIndex]
          this.pageNum = 1
          this.loadData()
        }
      })
    },
    
    // 搜索
    onSearch() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 清除搜索
    onClearSearch() {
      this.searchKeyword = ''
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载数据
    async loadData() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 添加筛选条件
        if (this.selectedType) {
          params.type = this.selectedType
        }
        
        // 根据当前激活的标签页加载不同状态的订单
        if (this.activeTab === 'refundable') {
          params.orderStatus = 1 // 可退款订单：已付款状态
        } else if (this.activeTab === 'refunded') {
          params.orderStatus = 3 // 已退款订单：已退款状态
        }
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }
        
        console.log('查询订单参数:', params)
        const response = await getDoorInfoList(params)
        
        if (response.code === 200) {
          if (this.pageNum === 1) {
            this.orderList = response.rows || []
          } else {
            this.orderList = [...this.orderList, ...(response.rows || [])]
          }
          
          this.hasMore = response.rows && response.rows.length === this.pageSize
          
          console.log('订单数据:', response.total, '条')
        } else {
          this.$modal.msgError(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/refund/detail?id=${item.id}`
      })
    },
    
    // 退款操作
    async refundOrder(item) {
      uni.showModal({
        title: '确认退款',
        content: `确定要对此订单进行退款操作吗？\n订单号：${item.orderNo}\n金额：¥${item.totalPrice}`,
        success: async (res) => {
          if (res.confirm) {
            try {
              this.$modal.loading('正在处理退款...')
              
              const data = {
                orderNo: item.orderNo
              }
              
              console.log('退款数据:', data)
              const response = await submitRefund(data)
              
              if (response.code === 200) {
                this.$modal.closeLoading()
                this.$modal.msgSuccess('退款申请已提交')
                // 刷新列表数据
                this.refreshData()
              } else {
                this.$modal.closeLoading()
                this.$modal.msgError(response.msg || '退款申请失败')
              }
            } catch (error) {
              this.$modal.closeLoading()
              console.error('退款申请失败:', error)
              this.$modal.msgError('网络异常，请稍后重试')
            }
          }
        }
      })
    },
    
    // 获取类型文本
    getTypeText(type) {
      const typeMap = {
        1: '运维费',
        3: '门禁卡',
        4: '人脸'
      }
      return typeMap[type] || '未知类型'
    },
    
    // 获取状态样式
    getStatusClass(item) {
      const classMap = {
        0: 'status-pending',   // 代付款
        1: 'status-approved',  // 已付款
        2: 'status-refunding', // 退款中
        3: 'status-rejected'   // 已退款
      }
      return classMap[item.orderStatus] || 'status-pending'
    },
    
    // 获取状态文本
    getStatusText(item) {
      const textMap = {
        0: '代付款',
        1: '已付款',
        2: '退款中',
        3: '已退款'
      }
      return textMap[item.orderStatus] || '未知状态'
    },
    
    // 获取支付渠道文本
    getPayChannelText(channel) {
      const channelMap = {
        '1': '微信支付',
        '2': '银行卡',
        // '3': '银行卡'
      }
      return channelMap[channel] || '未知渠道'
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }
}
</script>

<style lang="scss" scoped>
.refund-manage-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-add {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.tabs-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .tabs-container {
    display: flex;
    gap: 40rpx;
    justify-content: center;
    
    .tab-item {
      font-size: 30rpx;
      font-weight: bold;
      color: #666;
      padding-bottom: 10rpx;
      border-bottom: 4rpx solid transparent;
      
      &.active {
        color: #007AFF;
        border-bottom-color: #007AFF;
      }
    }
  }
}

.stats-section {
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stats-item {
    text-align: center;
    
    .stats-num {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.filter-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .filter-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
    }
    
    .filter-value {
      font-size: 26rpx;
      color: #666;
      flex: 1;
      text-align: right;
      margin-right: 20rpx;
    }
    
    .filter-arrow {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.search-section {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.order-list {
  padding: 20rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .item-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }
    
    .item-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-approved {
        background-color: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-refunding {
        background-color: #fff2e8;
        color: #fa8c16;
      }
      
      &.status-rejected {
        background-color: #f0f0f0;
        color: #666;
      }
      
      &.status-completed {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }
  
  .item-content {
    .item-row {
      display: flex;
      margin-bottom: 15rpx;
      
      .item-label {
        font-size: 26rpx;
        color: #666;
        width: 140rpx;
      }
      
      .item-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;
        
        &.amount {
          color: #ff4d4f;
          font-weight: bold;
        }
      }
    }
  }
  
  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .item-date {
      font-size: 24rpx;
      color: #999;
    }
    
    .item-actions {
      display: flex;
      gap: 20rpx;
      
      .action-btn {
        font-size: 24rpx;
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        
        &.refund {
          background-color: #fff7e6;
          color: #fa8c16;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}
</style> 